package com.study.manage.mvc.org.promotion;

import java.io.OutputStreamWriter;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.study.manage.dal.BlogCommentRepository;
import com.study.manage.dal.BlogGradeRepository;
import com.study.manage.dal.BlogHeartRepository;
import com.study.manage.dal.BlogMediaRepository;
import com.study.manage.dal.BlogRepository;
import com.study.manage.dal.EvaluateApplyRepository;
import com.study.manage.dal.EvaluateApplyWorkRepository;
import com.study.manage.dal.EvaluateApplyWorkVoteRepository;
import com.study.manage.dal.EvaluateGroupDetailRepository;
import com.study.manage.dal.EvaluatePriceRepository;
import com.study.manage.dal.EvaluateSingupPoolRepository;
import com.study.manage.dal.EvaluateWinnerRepository;
import com.study.manage.dal.UserRepository;
import com.study.manage.domain.Blog;
import com.study.manage.domain.EvaluateApply;
import com.study.manage.domain.EvaluateApplyWork;
import com.study.manage.domain.EvaluateGroupDetail;
import com.study.manage.domain.EvaluatePrice;
import com.study.manage.domain.EvaluateSingupPool;
import com.study.manage.domain.EvaluateWinner;
import com.study.manage.domain.Media;
import com.study.manage.domain.User;
import com.study.manage.domain.enumm.EAState;
import com.study.manage.domain.enumm.EvaluateApplyVerifyState;
import com.study.manage.domain.enumm.EvaluateVerify;
import com.study.manage.domain.enumm.LiveDieState;
import com.study.manage.dto.AjaxResponse;
import com.study.manage.dto.JsonResponseBean;
import com.study.manage.mvc.common.BaseController;
import com.study.manage.utils.CmnDateUtil;
import com.study.manage.utils.CmnStringUtils;
import com.study.manage.utils.MapUtils;

@Controller
@RequestMapping("org/evaluate/detail/jinji")
public class PromotionController extends BaseController {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private PromotionService promotionService;
    @Autowired
    private EvaluateApplyRepository evaluateApplyRepository;
    @Autowired
    private BlogMediaRepository blogMediaRepository;
    @Autowired
    private EvaluateSingupPoolRepository evaluateSingupPoolRepository;
    @Autowired
    private EvaluateApplyWorkRepository evaluateApplyWorkRepository;
    @Autowired
    private EvaluateWinnerRepository evaluateWinnerRepository;
    @Autowired
    private EvaluatePriceRepository evaluatePriceRepository;
    @Autowired
    private EvaluateGroupDetailRepository evaluateGroupDetailRepository;
    @Autowired
    private BlogHeartRepository blogHeartRepository;
    @Autowired
    private EvaluateApplyWorkVoteRepository evaluateApplyWorkVoteRepository;


    @RequestMapping(path = "info", method = RequestMethod.GET)
    public String usertemplate(Long id, ModelMap model) {

        model.put("number", promotionService.getBaseData(id));
        return "org/evaluate/usertemplate";
    }

    @RequestMapping(path = "work", method = RequestMethod.GET)
    public String worktemplate(Long id, ModelMap model) {

        model.put("number", promotionService.getBaseData(id));
        return "org/evaluate/worktemplate";
    }

    @ResponseBody
    @RequestMapping(path = "getUserData", method = RequestMethod.GET)
    public JsonResponseBean info_list(Date date, Long evaluateId, String name,
            EvaluateApplyVerifyState verifyState, EAState state,
            @PageableDefault(sort = {"createdAt"}, direction = Direction.DESC) Pageable pageable) {

        Page<EvaluateApply> page = evaluateApplyRepository.findByEvaluateIdAndDateAndName(
                evaluateId, date, name, verifyState, state, EvaluateVerify.Pass, pageable);
        Object obj = page.map(new Converter<EvaluateApply, Map<String, Object>>() {
            @Override
            public Map<String, Object> convert(EvaluateApply source) {
                Map<String, Object> map = MapUtils.convert(source);
                User user = userRepository.findOne(source.userId);
                map.put("userNumber", user.number);
                map.put("userName", user.name);
                map.put("userPhone", user.phone == null ? "--" : user.phone);
                if (source.referenceId != null) {
                    User refUer = userRepository.findOne(source.referenceId);
                    map.put("refName", refUer.name);
                } else {
                    map.put("refName", "--");
                }
                if (source.evaluatePriceId != null) {
                    EvaluatePrice ep = evaluatePriceRepository.findOne(source.evaluatePriceId);
                    map.put("epName", ep.title + "(" + ep.charge + ")");
                } else {
                    map.put("epName", "--");
                }
                EvaluateApplyWork eaw =
                        evaluateApplyWorkRepository.findByEvaluateApplyId(source.id);
                if (eaw != null) {
                    map.put("flg", "1");
                } else {
                    map.put("flg", "0");
                }
                map.put("verifyStateDesc", source.verifyState.desc);
                return map;
            }
        });
        return new JsonResponseBean(obj, true);
    }

    @Autowired
    private BlogCommentRepository blogCommentRepository;
    @Autowired
    private BlogRepository blogRepository;
    @Autowired
    private BlogGradeRepository blogGradeRepository;

    @ResponseBody
    @RequestMapping(path = "getWorkData", method = RequestMethod.GET)
    public JsonResponseBean info_list(Date date, Long evaluateId, String name,
            @RequestParam(defaultValue = "WORK") String verifyState, EAState state,
            @PageableDefault(sort = {"createdAt"}, direction = Direction.DESC) Pageable pageable) {

        Page<Blog> page = evaluateApplyRepository.findByEvaluateIdAndStateWork(evaluateId, name,
                null, date, pageable);
        Object obj = page.map(new Converter<Blog, Map<String, Object>>() {
            @Override
            public Map<String, Object> convert(Blog source) {
                EvaluateApply ea = evaluateApplyRepository.findOne(source.extId);
                Map<String, Object> map = MapUtils.convert(ea);
                User user = userRepository.findOne(source.userId);
                map.put("imgUrl",
                        "http://7xszyu.com1.z0.glb.clouddn.com/pic_avatar_" + user.number + ".jpg");
                map.put("userNumber", user.number);
                map.put("userName", user.name);
                if (ea.referenceId != null) {
                    User refUer = userRepository.findOne(ea.referenceId);
                    map.put("refName", refUer.name);
                }
                map.put("verifyStateDesc", ea.verifyState.desc);
                map.put("pwFen", "--");
                map.put("fen", "--");
                map.put("heartCount",
                        blogHeartRepository.sumCountByBlogIdAndState(source.id, LiveDieState.LIVE));
                map.put("voteCount", evaluateApplyWorkVoteRepository
                        .sumCountByBlogIdAndState(source.id, LiveDieState.LIVE));
                if (!StringUtils.isEmpty(source.extUrl2)) {
                    String[] urls = source.extUrl2.split(",");
                    map.put("fen", urls[0] + "/" + urls[1] + "人");
                    if (!urls[3].equals("0")) {
                        map.put("pwFen", urls[2] + "/" + urls[3] + "人");
                    }
                }
                map.put("uploadAt", source.createdAt);
                map.put("text", CmnStringUtils.isEmpty(source.text) ? "--" : source.text);
                List<Media> bs = blogMediaRepository.findMediaByBlogId(source.id);
                map.put("bs", bs);

                map.put("voteCount", evaluateApplyWorkVoteRepository
                        .countByEvaluateApplyIdAndState(ea.id, LiveDieState.LIVE));
                map.put("point", "0");
                EvaluateApplyWork eaw = evaluateApplyWorkRepository
                        .findByEvaluateApplyIdAndState(ea.id, LiveDieState.LIVE);
                if (eaw != null) {
                    map.put("blogId", eaw.blogId);
                    if (eaw.blogId != null) {
                        Blog b = blogRepository.findOne(eaw.blogId);
                        if (b != null && b.extUrl != null) {
                            map.put("point", b.extUrl);
                        }
                        map.put("likeCount", blogHeartRepository
                                .sumCountByBlogIdAndState(eaw.blogId, LiveDieState.LIVE));
                        map.put("commentCount", blogCommentRepository
                                .countByBlogIdAndState(eaw.blogId, LiveDieState.LIVE));
                        Float grade = blogGradeRepository
                                .sumPointByBlogIdAndIsEvaluateJury(eaw.blogId, true);
                        if (grade != null) {
                            map.put("pwPoint", new DecimalFormat(".0").format(grade));
                        }
                    }


                }
                return map;
            }
        });
        return new JsonResponseBean(obj, true);
    }

    @ResponseBody
    @RequestMapping(path = "getMedias", method = RequestMethod.GET)
    public AjaxResponse getMedias(Long id) {
        AjaxResponse ajax = new AjaxResponse(true);
        Blog blog = evaluateApplyRepository.findByAppalyEvaluateId(id);
        Map<String, Object> map = new HashMap<>();
        List<Media> medias = blogMediaRepository.findMediaByBlogId(blog.id);
        map.put("medias", medias);
        return ajax.setObj(map);
    }

    @ResponseBody
    @Transactional
    @RequestMapping(path = "updateapply", method = RequestMethod.POST)
    public JsonResponseBean updateEvaluateApply(Long idp, Long id,
            EvaluateApplyVerifyState verifyState) {

        Date date = new Date();
        if (verifyState == EvaluateApplyVerifyState.DD) {
            date = null;
        } else {
            EvaluateApply apply = evaluateApplyRepository.findOne(id);
            if (apply != null) {
                EvaluateGroupDetail evaluateGroupDetail = evaluateGroupDetailRepository
                        .findByEvaluateIdAndState(apply.evaluateId, LiveDieState.LIVE).get(0);
                if (evaluateGroupDetail != null && evaluateGroupDetail.nextEvaluateId != null) {
                    EvaluateSingupPool esp = new EvaluateSingupPool();
                    esp.evaluateId = evaluateGroupDetail.nextEvaluateId;
                    esp.userId = apply.userId;
                    esp.evaluateApplyId = id;
                    evaluateSingupPoolRepository.save(esp);
                }
            }
            EvaluateApplyWork work = evaluateApplyWorkRepository.findByEvaluateApplyId(id);
            if (work != null) {
                EvaluateWinner ew = new EvaluateWinner();
                ew.evaluateApplyId = id;
                ew.evaluateApplyWorkId = work.id;
                ew.evaluateId = apply.evaluateId;
                ew.userId = apply.userId;
                evaluateWinnerRepository.save(ew);
            }
        }
        evaluateApplyRepository.update(id, verifyState, date);
        return new JsonResponseBean(promotionService.getBaseData(idp), true);
    }

    @ResponseBody
    @Transactional
    @RequestMapping(path = "updateremark", method = RequestMethod.POST)
    public AjaxResponse updateRemark(Long id, String remark) {

        AjaxResponse ajax = new AjaxResponse(true);
        evaluateApplyRepository.updateRemark(id, remark);
        return ajax;
    }

    @RequestMapping(path = "exportExecl", method = RequestMethod.GET)
    public void exportExecl(Long id, HttpServletResponse response) throws Exception {

        List<EvaluateApply> list = evaluateApplyRepository.findEvaluateApplys(id, null, null,
                EvaluateVerify.Pass, null);
        StringBuilder context = new StringBuilder("报名时间,参赛编号,用户(ID),电话,渠道,评审\n");
        for (EvaluateApply source : list) {
            User user = userRepository.findOne(source.userId);
            String refName = "";
            if (source.referenceId != null) {
                User refUer = userRepository.findOne(source.referenceId);
                refName = refUer.name;
            };
            context.append(CmnDateUtil.formatDate(source.createdAt.toString())).append(",")
                    .append(source.number + "\t").append(",")
                    .append(user.name + "(" + user.number + ")").append(",")
                    .append(user.phone == null ? "" : user.phone).append(",").append(refName)
                    .append(",").append(source.verifyState.desc).append("\n");
        };
        String nowDate = "晋级管理(全部).csv";
        String fileName = new String(nowDate.getBytes("UTF-8"), "iso-8859-1");// 为了解决中文名称乱码问题
        OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
        // 要输出的内容
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        osw.write(new String(new byte[] {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF}));
        osw.write(context.toString());
        osw.flush();
    }

}

